package com.example.sps.utils;

import com.example.sps.commons.ServiceCode;
import com.example.sps.commons.ServiceException;
import com.example.sps.pojo.vo.EmpToken;
import io.jsonwebtoken.*;
import org.springframework.boot.web.embedded.jetty.JettyServerCustomizer;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * @ProjectName: Sps
 * @Titile: JWTUtils
 * @Author: nency
 * @Description: TODO
 */
public class JWTUtils {
    public static final int TOKEN_EXPIRE = 7*24*60*60*1000;
    public static final String TOKEN_SIGN = "cqupt20240719";

    /**
     * 生成员工token
     * @param empToken
     * @return
     */
    public static String generateToken(EmpToken empToken){
        String subject = empToken.getPhone();
        Date now = new Date();
        long time = now.getTime();
        long expireTime = time + TOKEN_EXPIRE;
        Date expireDate = new Date(expireTime);
        return Jwts.builder().setSubject(subject)
                .setIssuedAt(now)
                .setExpiration(expireDate)
                .claim("id",empToken.getId())
                .claim("phone",empToken.getPhone())
                .signWith(SignatureAlgorithm.HS256,TOKEN_SIGN)
                .compact();
    }

    public static Claims validateToken(String token){
        Claims claims = null;
        try {
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(TOKEN_SIGN).parseClaimsJws(token);
            claims = claimsJws.getBody();
        } catch (ExpiredJwtException e) {
            throw new ServiceException(ServiceCode.ERROR_TOKEN_EXPIRE,"token过期");
        } catch (UnsupportedJwtException | MalformedJwtException |
                 SignatureException | IllegalArgumentException e) {
            throw new ServiceException(ServiceCode.ERROR_TOKEN_UNKNOWN,"token无效");
        }
        return claims;
    }

    public static EmpToken parseToken(String token){
        Claims claims = validateToken(token);
        Integer id = Integer.valueOf(claims.get("id").toString());
        String phone = claims.get("phone").toString();
        EmpToken empToken = new EmpToken();
        empToken.setId(id);
        empToken.setPhone(phone);
        return empToken;
    }

//    public static void main(String[] args) {
//        EmpToken empToken = new EmpToken();
//        empToken.setId(1001);
//        empToken.setPhone("123456789012");
//        String token = generateToken(empToken);
//        System.out.println(token);
//        validateToken(token);
//        EmpToken parsedToken = parseToken(token);
//        System.out.println(parsedToken);
//    }
}

